﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using Gift.Model.ENUM;
using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.warehouse
{
    public partial class warehouseGoodsStatic : BaseAdmin
    {
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }


        private string GetSql()
        {
            string sql = "select convert(varchar(18),g.goodsId) +'_' + isnull(convert(varchar(18),wg.modelTypeId),'') as goodsId,g.goodsName + '_' + g.goodsCode as goodsName ,(select modelTypeName from tbModelType where modelTypeId=wg.modelTypeId) as modelTypeName, "
                        + " isnull(sum(wg.goodsCount),0) -  isnull((select sum(isnull(goodsCount,0))  from tbWarehouseGoodsOut where goodsId = g.goodsId and modelTypeId = wg.modelTypeId and warehouseId=wg.warehouseId ),0) "
                        +" as goodsCount  , wg.warehouseId,w.warehouseName  "
                        +"  from tbWarehouseGoods wg join tbGoods g on wg.goodsId = g.goodsId join tbWarehouse w on wg.warehouseId = w.id "
                        +" group by  g.goodsId,g.goodsCode,g.goodsName,wg.warehouseId,w.warehouseName,wg.modelTypeId";
            if (!string.IsNullOrEmpty(this.txtGoodsName.Text.Trim()))
            {
                sql = sql + string.Format(" having g.goodsName like '%{0}%' ", this.txtGoodsName.Text.Trim());
            }

            return sql;
        }


        private void GridViewBind(string Sqlsort)
        {
            string sql = GetSql();
            if (Sqlsort == "")
            {
                sql = sql + " order by g.goodsId desc ";
            }
            else
            {
                sql = sql + Sqlsort;
            }

            DataTable tempTable = SQLAccess.GreatDs(sql).Tables[0];
            DataTable table = GetResultTable(tempTable);


            // 获取GridView排序数据列及排序方向
            string sortExpression = this.GridView1.Attributes["SortExpression"];
            string sortDirection = this.GridView1.Attributes["SortDirection"];
            // 根据GridView排序数据列及排序方向设置显示的默认数据视图
            if ((!string.IsNullOrEmpty(sortExpression)) && (!string.IsNullOrEmpty(sortDirection)))
            {
                table.DefaultView.Sort = string.Format("{0} {1}", sortExpression, sortDirection);
            }

            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();
            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + this.GridView1.PageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + table.Rows.Count.ToString() + "个记录";
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (this.GridView1.PageCount == 1)
            {
                this.btnFirst.Visible = true;
                this.btnPrev.Visible = true;
                this.btnNext.Visible = true;
                this.btnLast.Visible = true;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (this.GridView1.PageCount == 1) ? this.GridView1.PageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = this.GridView1.PageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            if (this.GridView1.PageCount > 0)
            {
                for (int i = 1; i <= this.GridView1.PageCount; i++)
                {
                    this.ddlCurrentPage.Items.Add(i.ToString());
                }
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }
        }

        DataTable GetResultTable(DataTable tempTable)
        {
            DataTable table = new DataTable();

            if (tempTable != null)
            {

                DataColumn[] keyColumn = new DataColumn[1];
                keyColumn[0] = new DataColumn("编号", Type.GetType("System.String"));

                table.Columns.Add(keyColumn[0]);

                table.Columns.Add("商品名称", Type.GetType("System.String"));
                table.Columns.Add("商品型号", Type.GetType("System.String"));
                table.Columns.Add("总计", Type.GetType("System.String"));
                table.PrimaryKey = keyColumn;

                DataRow drTemp;
                foreach (DataRow dr in tempTable.Rows)
                {
                    if (!table.Columns.Contains(dr["warehouseName"].ToString()))
                    {
                        table.Columns.Add(dr["warehouseName"].ToString(), Type.GetType("System.String"));
                    }
                }

                foreach (DataRow dr in tempTable.Rows)
                {
                    DataRow subRow = table.Rows.Find(dr["goodsId"].ToString());
                    if (subRow != null)
                    {
                        subRow[dr["warehouseName"].ToString()] = dr["goodsCount"].ToString();
                        subRow["总计"] = int.Parse(subRow["总计"].ToString()) + int.Parse(dr["goodsCount"].ToString());
                    }
                    else
                    {
                        drTemp = table.NewRow();
                        drTemp["编号"] = dr["goodsId"].ToString();
                        drTemp["商品名称"] = dr["goodsName"].ToString();
                        drTemp["商品型号"] = dr["modelTypeName"].ToString();
                        drTemp[dr["warehouseName"].ToString()] = dr["goodsCount"].ToString();
                        drTemp["总计"] = dr["goodsCount"].ToString();
                        table.Rows.Add(drTemp);
                    }
                }
            }
            return table;

        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!base.IsPostBack)
            {
                base.ValidateLoginRule(ERule.WarehousesGoodsStatic);
                this.GridViewBind("");
            }
        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");
        }

        protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
        {
            this.GridViewBind("");
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            // 从事件参数获取排序数据列
            string sortExpression = e.SortExpression.ToString();

            // 假定为排序方向为“顺序”
            string sortDirection = "ASC";

            // “ASC”与事件参数获取到的排序方向进行比较，进行GridView排序方向参数的修改
            if (sortExpression == this.GridView1.Attributes["SortExpression"])
            {
                //获得下一次的排序状态
                sortDirection = (this.GridView1.Attributes["SortDirection"].ToString() == sortDirection ? "DESC" : "ASC");
            }

            // 重新设定GridView排序数据列及排序方向
            this.GridView1.Attributes["SortExpression"] = sortExpression;
            this.GridView1.Attributes["SortDirection"] = sortDirection;

            this.GridViewBind("");
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//设置导出文件的名称   
            string sql = GetSql();

            sql = sql + " order by goodsId desc ";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            DataTable tb = GetResultTable(table);
            //table.Columns["goodsId"].ColumnName = "商品编号";
            //string sTitle = string.Empty;
         //   ExcelHelper.ExportDataTableToExcel(tb, fileName, "商品库存统计");
        }

    }
}